package com.example.web.servlet;

import com.example.common.Result;
import com.example.model.User;
import com.example.service.TripService;
import com.example.service.impl.TripServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/cancel")
public class ConceleServlet extends HttpServlet {
    private TripService tripService = new TripServiceImpl();
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        Result result = null;
        if (user == null) {
            // 用户没有登录
            result = Result.fail(300 , "请先登录");
            String result_str = objectMapper.writeValueAsString(result);
            resp.getWriter().write(result_str);
            return;
        }
        String id = req.getParameter("id");
        System.out.println(id);
        boolean flag = tripService.concele(id,user.getUid());
        System.out.println(user);

        if (flag) {
            // 购买成功
            result = Result.success("退票成功");
        } else {
            // 购买失败
            result = Result.fail(400 , "退票失败");
        }
        String result_str = objectMapper.writeValueAsString(result);
        resp.getWriter().write(result_str);
    }
}
